package com.example.elderlycare.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elderlycare.dao.entity.Role;
import com.example.elderlycare.dao.entity.User;
import com.example.elderlycare.dao.mapper.RoleMapper;
import com.example.elderlycare.dao.mapper.UserMapper;
import com.example.elderlycare.exception.PasswordErrorException;
import com.example.elderlycare.exception.SignTokenException;
import com.example.elderlycare.exception.UserNotFoundException;
import com.example.elderlycare.service.LoginService;
import com.example.elderlycare.service.entity.LoginResponseBody;
import com.example.elderlycare.utils.PasswordMD5;
import com.example.elderlycare.utils.Token;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    Token token;

    @Override
    public LoginResponseBody userLoginService(String username, String password)
            throws UserNotFoundException, PasswordErrorException, SignTokenException {

        // 构造查询构造器，根据用户名查找
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);

        // 未找到用户
        if (user == null) {
            throw new UserNotFoundException();
        }

        // 密码错误
        if (!user.getPassword().equals(PasswordMD5.getPasswordMD5(password))) {
            throw new PasswordErrorException();
        }

        String token;
        try {
            token = this.token.sign(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SignTokenException();
        }
        // 获取用户角色信息
        Role userRole = roleMapper.selectById(user.getRoleID());
        return LoginResponseBody.builder()
                .id(user.getId())
                .token(token)
                .username(user.getUsername())
                .nickname(user.getNickname())
                .role(userRole.getValue())
                .build();

    }
}
